﻿
namespace HSS.Xaml.UI.Data
{
	#region Using Directives
	using System;
	using System.Windows.Data;
	#endregion

	#region ByteConverter
	/// <summary>
	/// ByteValueConverter converts doubles into a string such as 10GB or 500 bytes
	/// </summary>
	public class ByteValueConverter : IValueConverter
	{
		#region IValueConverter Members
		/// <summary>
		/// Convert doubles into a string such as 10GB or 500 bytes
		/// </summary>
		/// <param name="value">The value to convert</param>
		/// <param name="targetType">The destination type</param>
		/// <param name="parameter">Optional and unused parameter</param>
		/// <param name="culture">Curernt Thread Culture</param>
		/// <returns>A string contains the size and size indicator as a string</returns>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if (value == null)
				return "0 KB";

			try
			{
				var fileSize = double.Parse(value.ToString(), culture);

				if (fileSize < 1024.0)
					return string.Format(culture, "{0:N0} bytes", fileSize);

				if (fileSize < 1048576.0)
					return string.Format(culture, "{0:N1} KB", fileSize / 1024.0);

				if (fileSize < 1073741824.0)
					return string.Format(culture, "{0:N1} MB", fileSize / 1048576.0);

				return string.Format(culture, "{0:N1} GB", fileSize / 1073741824.0);
			}
			catch
			{
				return "0 KB";
			}
		}
		/// <summary>
		/// We only support one-way binding, so we don't implement this.
		/// </summary>
		/// <param name="value"></param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns></returns>
		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			throw new NotImplementedException();
		}
		#endregion
	}
	#endregion
}
